﻿using MixingStation.LTWebService;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;

namespace MixingStation
{
    public partial class FormLogin : Form
    {
        //登陆过的用户
        private string m_HaveLoginNameStr = "";
        //当前登录用户
        private userWs m_CurrentUser = null;
        public userWs CurrentUser
        {
            get { return m_CurrentUser; }
        }
        //是否联网
        private bool m_IsOnline = true;
        public bool IsOnline
        {
            get { return m_IsOnline; }
        }

        public FormLogin()
        {
            InitializeComponent();
        }

        private void FormLogin_Load(object sender, EventArgs e)
        {
            m_HaveLoginNameStr = ConfigurationManager.AppSettings["UserNames"];

            foreach (string name in m_HaveLoginNameStr.Split(','))
                cb_UserName.Items.Add(name);
            cb_UserName.SelectedIndex = 0;
        }

        private void txt_Password_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)//回车登录
            {
                login();
            }
        }
        private void btn_login_Click(object sender, EventArgs e)//按键登录
        {
            login();
        }

        private void login()
        {
            string name = cb_UserName.Text.Trim();
            string password = txt_Password.Text.Trim();
            //判断是否联网
            using (LTCardAPIServiceClient client = new LTCardAPIServiceClient())
            {
                m_IsOnline = ServerCommonHelper.IsWebServiceAvaiable(client.Endpoint.Address.Uri);
                try
                {
                    if (m_IsOnline)
                    {
                        m_CurrentUser = client.login(name, password);
                        //同步本地时间
                        if (m_CurrentUser != null)
                            UpdateLocalTime();
                        //json登录
                        if (!ServerCommonHelper.JsonLogin(name, password))
                        {
                            MessageBox.Show("Json登录失败,详见日志");
                            return;
                        }
                    }
                    else
                    {
                        DialogResult dr = MessageBox.Show("当前处于断网状态下，是否使用本地用户进行登录", "询问", MessageBoxButtons.YesNo);
                        if (dr == DialogResult.No)
                            return;
                        if (!SingleLogin(name, password))
                            return;
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.error("用户登录异常：" + ex.ToString());
                    MessageBox.Show("用户登录异常:" + ex.Message);
                    return;
                }
            }
            if (m_CurrentUser == null)
                return;
            if (cb_savename.Checked)
            {
                if (!m_HaveLoginNameStr.Split(',').Contains(name))
                {
                    m_HaveLoginNameStr += "," + name;
                    Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    cfa.AppSettings.Settings["UserNames"].Value = m_HaveLoginNameStr;
                    cfa.Save();
                    ConfigurationManager.RefreshSection("appSettings");
                }
            }
            this.DialogResult = DialogResult.OK;
        }

        private bool SingleLogin(string code, string password)
        {
            string sql = "select * from [User] where UserName = '" + code + "'";
            DataTable dt = CommonHelper.DoSelectOpreation(sql);
            if (dt == null || dt.Rows.Count == 0)
            {
                MessageBox.Show("该用户不存在，请重新输入！");
                cb_UserName.Focus();
                return false;
            }
            sql = "select * from [User] where UserName = '" + code + "' and [Password] = '" + password + "'";
            dt = CommonHelper.DoSelectOpreation(sql);
            if (dt == null || dt.Rows.Count == 0)
            {
                MessageBox.Show("密码不正确，请重新输入！");
                cb_UserName.Focus();
                return false;
            }
            //构建UserWS
            string id = dt.Rows[0]["Id"].ToString();
            string name = dt.Rows[0]["EmployeeName"].ToString();
            m_CurrentUser = CreateUserWs(id, code, name, password);
            return true;
        }

        private userWs CreateUserWs(string id, string code, string name, string password)
        {
            userWs user = new userWs();
            user.id = id;
            user.userame = code;
            user.employeeName = name;
            user.password = password;
            return user;
        }

        //同步本地时间与服务器时间一致
        private void UpdateLocalTime()
        {
            try
            {
                using (LTCardAPIServiceClient client = new LTCardAPIServiceClient())
                {

                    DateTime dt = client.getDateTime();//设置系统时间
                    CommonHelper.SYSTEMTIME systemTime = new CommonHelper.SYSTEMTIME();
                    systemTime.FromDateTime(dt);
                    CommonHelper.SetLocalTime(ref systemTime);
                }
            }
            catch (Exception ex)
            {
                LogHelper.error("同步本地时间与服务器时间一致异常：" + ex.Message);
            }
        }

        private void btn_cancel_Click(object sender, EventArgs e)//取消登录
        {
            this.Close();
        }
    }
}
